<?php
/**
 * @package site
 */
class InvestProgram extends DataObject implements PermissionProvider {
    private static $singular_name = "Invest Program";
    private static $plural_name = "Invest Program";
	
	private static $setting_table = array(
		'level1' => array('max_day' => 160, 'percentage' => 0.01),
		'level2' => array('max_day' => 180, 'percentage' => 0.01),
		'level3' => array('max_day' => 200, 'percentage' => 0.01),
		'level4' => array('max_day' => 220, 'percentage' => 0.01),
		'level5' => array('max_day' => 240, 'percentage' => 0.01),
		'level6' => array('max_day' => 260, 'percentage' => 0.01)
	);
    
    private static $db = array(
    	'Percentage' => 'Percentage',
    	'MaxDay' => 'Int',
    	'TotalPayout' => 'Currency',
    	'NextPayout' => 'Date',
    	'PaidDay' => 'Int',
    	'IsClosed' => 'Boolean'
    );
	
	private static $has_one = array(
		'Member' => 'Member',
		'Group' => 'Group',
		'OrderPackage' => 'OrderPackage'
	);
	
	private static $has_many = array(
        'Payouts' => 'InvestProgramPayout'
    );
	
	private static $default_sort = "Created DESC";

    private static $searchable_fields = array(
    	'Created',
    	'Member.FirstName',
    	'Member.Surname',
    	'Member.Username',
    	'GroupID',
    	'OrderPackage.BV',
    	'Percentage',
        'TotalPayout',
        'NextPayout',
        'PaidDay',
        'IsClosed'
    );

    private static $summary_fields = array(
    	'Created.Nice',
    	'Member.Username',
    	'Member.Name',
    	'Group.Title',
    	'OrderPackage.BV',
    	'Percentage.Nice',
        'TotalPayout',
        'NextPayout.Nice',
        'PaidDay',
        'IsClosed.Nice'
    );
	
	private static $casting = array(
		'InvestAmount' => 'Currency',
		'DailyPayout' => 'Currency',
		'MaxPayout' => 'Currency'
	);
	
	static function create_program($orderid){
		if($order = OrderPackage::get()->byID($orderid)){
			$setting_table = Config::inst()->get('InvestProgram', 'setting_table');
			$current_setting = $setting_table[$order->UpgradeGroup()->Code];
			$next_payout = date("Y-m-d", strtotime("+1 day", time()));
			$dw = date("w", strtotime($next_payout));
			if($dw == 0){
				$next_payout = strtotime("+1 day", strtotime($next_payout));
			}
			else if($dw == 6){
				$next_payout = strtotime("+2 day", strtotime($next_payout));
			}
			$id = InvestProgram::create()
			->setField('Percentage', $current_setting['percentage'])
			->setField('MaxDay', $current_setting['max_day'])
			->setField('NextPayout', $next_payout)
			->setField('MemberID', $order->MemberID)
			->setField('GroupID', $order->UpgradeGroupID)
			->setField('OrderPackageID', $order->ID)
			->write();
			
			return $id;
		}
	}
	
	public function fieldLabels($includerelations = true) {
		$labels = parent::fieldLabels($includerelations);
		
		$labels['Created'] = _t('InvestProgram.DATE', 'Date');
		$labels['Created.Nice'] = _t('InvestProgram.DATE', 'Date');
		$labels['Percentage'] = _t('InvestProgram.PERCENTAGE', 'Percentage');
		$labels['Percentage.Nice'] = _t('InvestProgram.PERCENTAGE', 'Percentage');
		$labels['MaxDay'] = _t('InvestProgram.MAX_PAYOUT_DAY', 'Max Payout Day');
		$labels['PaidDay'] = _t('InvestProgram.PAID_DAY', 'Paid Day');
		$labels['TotalPayout'] = _t('InvestProgram.TOTAL_PAYOUT', 'Total Payout');
		$labels['NextPayout'] = _t('InvestProgram.NEXT_PAYOUT', 'Next Payout');
		$labels['NextPayout.Nice'] = _t('InvestProgram.NEXT_PAYOUT', 'Next Payout');
		$labels['IsClosed'] = _t('InvestProgram.IS_CLOSED', 'Is Closed?');
		$labels['IsClosed.Nice'] = _t('InvestProgram.IS_CLOSED', 'Is Closed?');
		$labels['Payouts'] = _t('InvestProgram.PAYOUT_DETAILS', 'Payout Details');
		$labels['Group'] = _t('InvestProgram.GROUP', 'Group');
		$labels['GroupID'] = _t('InvestProgram.GROUP', 'Group');
		$labels['Group.Title'] = _t('InvestProgram.GROUP', 'Group');
		$labels['OrderPackage'] = _t('InvestProgram.PACKAGE', 'Package');
		$labels['OrderPackage.Title'] = _t('InvestProgram.PACKAGE', 'Package');
		$labels['OrderPackage.BV'] = _t('InvestProgram.INVEST_AMOUNT', 'Invest Amount');
		$labels['InvestAmount'] = _t('InvestProgram.INVEST_AMOUNT', 'Invest Amount');
		$labels['Member.Username'] = _t('InvestProgram.USERNAME', 'Username');
		$labels['Member'] = _t('InvestProgram.NAME', 'Name');
		$labels['Member.Name'] = _t('InvestProgram.NAME', 'Name');
		$labels['Member.FirstName'] = _t('InvestProgram.FIRSTNAME', 'First Name');
		$labels['Member.Surname'] = _t('InvestProgram.SURNAME', 'Surname');
		return $labels;	
	}
	
	function getTotalPayoutWithLink(){
        $view_link = Controller::join_links(InvestProgramPage::get()->first()->Link('view'), $this->ID);
        return sprintf('<a href="%s" title="%s" data-title="%s" rel="popup tooltip" data-modal-lg="true">%s</a>', $view_link, _t('InvestProgram.CLICK_PAYOUT_DETAILS', 'Click here to view payout details'), _t('InvestProgram.PAYOUT_DETAILS', 'Payout Details'), $this->TotalPayout);
    }
	
	function getInvestAmount(){
		if($this->OrderPackage()->exists()){
			return $this->OrderPackage()->BV;
		}
		else{
			$package = Package::get()->filter('Type', 'Register')->find('UpgradeGroupID', $this->Group()->ID);
			$price = $package ? $package->Prices()->first() : 0;
			return $price ? $price->BV : 0;
		}
	}
	
	function getMaxPayout(){
		return $this->MaxDay * $this->InvestAmount * $this->Percentage;
	}
	
	function getDailyPayout(){
		return $this->InvestAmount * $this->Percentage;
	}
	
    function canView($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('VIEW_InvestProgram');
    }

    function canEdit($member = false) {
    	if(!$this->exists() && $this->canCreate($member)){
    		return true;
    	}
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('EDIT_InvestProgram');
    }

    function canDelete($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('DELETE_InvestProgram');
    }

    function canCreate($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('CREATE_InvestProgram');
    }

    public function providePermissions() {
        return array(
            'VIEW_InvestProgram' => array(
                'name' => _t('InvestProgram.PERMISSION_VIEW', 'Allow view access right'),
                'category' => _t('InvestProgram.PERMISSIONS_CATEGORY', 'Invest Program')
            ),
            'EDIT_InvestProgram' => array(
                'name' => _t('InvestProgram.PERMISSION_EDIT', 'Allow edit access right'),
                'category' => _t('InvestProgram.PERMISSIONS_CATEGORY', 'Invest Program')
            ),
            'DELETE_InvestProgram' => array(
                'name' => _t('InvestProgram.PERMISSION_DELETE', 'Allow delete access right'),
                'category' => _t('InvestProgram.PERMISSIONS_CATEGORY', 'Invest Program')
            ),
            'CREATE_InvestProgram' => array(
                'name' => _t('InvestProgram.PERMISSION_CREATE', 'Allow create access right'),
                'category' => _t('InvestProgram.PERMISSIONS_CATEGORY', 'Invest Program')
            )
        );
    }
}
?>
